import { fetchAssetDetail, fetchAssetList } from '../services/api';

export default {
  namespace: 'assetList',
  state: {
    loading: true,
    data: [],
    assetDetail: undefined,
  },
  effects: {
    *fetchList({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        paylaod: true,
      });

      const response = yield call(fetchAssetList, payload);

      yield put({
        type: 'loadAssetList',
        payload: response,
      });

      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *fetchDetail({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(fetchAssetDetail, payload);

      yield put({
        type: 'loadAssetDetail',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    loadAssetList(state, { payload }) {
      return {
        ...state,
        data: payload.assets,
        totalPage: payload.total_page,
      };
    },
    loadAssetDetail(state, { payload }) {
      return {
        ...state,
        assetDetail: payload,
      };
    },
  },
};

